package edu.pw.p2pclient.logic;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import edu.pw.p2pclient.R;
import edu.pw.p2pclient.data.DownloadNode;
import edu.pw.p2pclient.data.Resource;
import edu.pw.p2pclient.networking.CommunicationService;
import edu.pw.p2pclient.utils.ApplicationContext;

public class PushDownloadAdapter extends ArrayAdapter<DownloadNode> {

	private ViewHolder mViewHolder = null;
	private FragmentActivity mParentActivity = null;

	public PushDownloadAdapter() {
		super(ApplicationContext.get(), R.layout.download_row);
	}

	public void setParentActivity(FragmentActivity availableFragment) {
		mParentActivity = availableFragment;
	}

	@Override
	public void add(final DownloadNode node) {

		if (getPosition(node) == -1) {
			Handler handler = new Handler(Looper.getMainLooper());
			handler.post(new Runnable() {

				@Override
				public void run() {

					PushDownloadAdapter.super.add(node);
				}
			});
		}
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater
					.inflate(R.layout.download_row, parent, false);

			mViewHolder = new ViewHolder();

			mViewHolder.filename = (TextView) convertView
					.findViewById(R.id.fileNameText);
			mViewHolder.size = (TextView) convertView
					.findViewById(R.id.sizeText);
			mViewHolder.actionButton = (ImageView) convertView
					.findViewById(R.id.statusIndicatorImage);
			mViewHolder.progress = (ProgressBar) convertView
					.findViewById(R.id.progressBar);

			convertView.setTag(mViewHolder);
		} else {
			mViewHolder = (ViewHolder) convertView.getTag();
		}

		final DownloadNode d = getItem(position);

		mViewHolder.filename.setText(d.getName());
		mViewHolder.size.setText(String.valueOf(d.getSize()));

		switch (d.getState()) {
		case DownloadNode.DOWNLOADING:
			mViewHolder.actionButton.setImageResource(R.drawable.pause);
			break;
		case DownloadNode.CANCELLED:
			mViewHolder.actionButton.setImageResource(R.drawable.remove);
			break;
		case DownloadNode.DONE:
			mViewHolder.actionButton.setImageResource(R.drawable.done);
			break;
		case DownloadNode.QUEUED:
			mViewHolder.actionButton.setImageResource(R.drawable.queued);
			break;
		default:
			mViewHolder.actionButton.setImageResource(R.drawable.play);
		}
		if (CommunicationService.getInstance() == null
				|| !CommunicationService.isRunning() || d.isDone()) {
			mViewHolder.actionButton.setOnClickListener(null);
		} else {
			mViewHolder.actionButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					switch (d.getState()) {
					case DownloadNode.DOWNLOADING:
						d.setState(DownloadNode.PAUSED);
						DownloadManager.getInstance().downloadNext(d);
						break;
					case DownloadNode.PAUSED:
						if (d.getSharingInfo().isPasswordProtected()
								&& d.getSharingInfo().getPassword().equals("")) {
							AlertDialog.Builder alert = new AlertDialog.Builder(
									mParentActivity);

							alert.setTitle(R.string.enter_password);
							alert.setMessage(R.string.enter_password_full);

							final EditText input = new EditText(
									ApplicationContext.get());
							alert.setView(input)
									.setPositiveButton(
											android.R.string.ok,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int whichButton) {

													if (input.getText()
															.toString()
															.equals("")) {
														Toast.makeText(
																getContext(),
																R.string.you_must_enter_password,
																Toast.LENGTH_SHORT)
																.show();
														return;
													}
													d.getSharingInfo()
															.setPassword(
																	input.getText()
																			.toString());
													d.setState(DownloadNode.QUEUED);
													DownloadManager
															.getInstance()
															.startDownload(d);
												}
											})
									.setNegativeButton(
											R.string.cancel,
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int whichButton) {
													input.setText("");
												}
											});

							alert.show();
						} else {
							d.setState(DownloadNode.QUEUED);
							DownloadManager.getInstance().startDownload(d);
						}
						break;
					case DownloadNode.QUEUED:
						Toast.makeText(getContext(), R.string.no_free_slots,
								Toast.LENGTH_SHORT).show();
						break;
					}
				}
			});
		}
		mViewHolder.progress.setProgress(d.getReadyPercent());

		return convertView;
	}

	public void clearDownloaded() {
		for (int i = getCount() - 1; i >= 0; --i) {
			DownloadNode node = getItem(i);
			if (node.isDone() || node.isCancelled()) {
				remove(node);
			}
		}
		notifyDataSetChanged();
		AvailableManager.getInstance().getAdapter().resourcesDeletedFromQueue();
	}

	private class ViewHolder {
		TextView filename;
		TextView size;
		ImageView actionButton;
		ProgressBar progress;
	}

	public void addAllPush(ArrayList<Resource> resources) {
		for (Resource res : resources) {
			if (res.isPush()) {
				DownloadNode node = new DownloadNode(res);
				if (getPosition(node) == -1) {
					node.setState(DownloadNode.QUEUED);
					add(node);
					DownloadManager.getInstance().startDownload(node);
				}
			}
		}
	}
}
